package com.kingbook.services;

import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Customer;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2019-12-18 21:37:35
 * @Version 1.0
 */
@Slf4j
@Service
public class CustomerService extends SupportService {

    @PostConstruct
    private void init() {
        setNamespace("Customer");
    }

    public JSONResult updateCustomer( Map<String, Object> param ) {
        int mid = MapUtils.getIntValue(param, "mid");
        int id = MapUtils.getIntValue(param, "id");
        String name = MapUtils.getString(param, "name");
        Customer customer = queryCustomerByName( mid, name);
        if (customer != null && customer.getId() != id && name.equals(customer.getName()))
            return JSONResult.failed(name + " 已添加");
        return id > 0 ? modify(param) : save(param);
    }

    public int getCustomerId(int mid, String name, boolean insert) {
        if (StringUtils.isNotEmpty(name)) {
            Map<String, Object> param = Maps.newHashMap();
            param.put("mid", mid);
            param.put("name", name);
            Customer customer = findObject("queryCustomer", param, Customer.class);
            if (customer != null) {
                return customer.getId();
            } else if (insert) {
                JSONResult result = insertReturnKey("insert", param);
                return Integer.parseInt(result.getMsg());
            }
        }
        return 0;
    }

    public JSONResult queryCustomer(Integer id, Integer mid) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("id", id);
        param.put("mid", mid);
        return query("queryCustomer", param);
    }

    public Customer queryCustomerByName(Integer mid, String name) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("mid", mid);
        param.put("name", name);
        return findObject("queryCustomer", param, Customer.class);
    }

    public JSONResult queryCustomerAndWorkspace(Map<String, Object> param) {
        return query("queryCustomerAndWorkspace", param);
    }
}
